package com.gradecak.alfresco.mvc.jackson;

import java.text.SimpleDateFormat;


import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.namespace.QName;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.module.SimpleModule;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;

import com.gradecak.alfresco.mvc.converter.QnameDeserializer;
import com.gradecak.alfresco.mvc.converter.QnameSerializer;

public class JacksonPostProcessor implements BeanPostProcessor {
  public static final String JSON_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";

  @Autowired
  private ServiceRegistry serviceRegistry;

  public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    return bean;
  }

  public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof AnnotationMethodHandlerAdapter) {
      AnnotationMethodHandlerAdapter adapter = (AnnotationMethodHandlerAdapter) bean;
      HttpMessageConverter<?>[] converters = adapter.getMessageConverters();
      for (HttpMessageConverter<?> converter : converters) {
        if (converter instanceof MappingJacksonHttpMessageConverter) {
          MappingJacksonHttpMessageConverter jsonConverter = (MappingJacksonHttpMessageConverter) converter;

          ObjectMapper objectMapper = new ObjectMapper();
          SimpleModule module = new SimpleModule("Alfresco MVC Module", new Version(1, 0, 0, null));
          module.addSerializer(QName.class, new QnameSerializer(serviceRegistry));
          module.addDeserializer(QName.class, new QnameDeserializer(serviceRegistry));

          objectMapper.setDateFormat(new SimpleDateFormat(JSON_DATE_FORMAT));
          objectMapper.registerModule(module);

          jsonConverter.setObjectMapper(objectMapper);
        }
      }
    }
    return bean;
  }

}
